package com.itrip.auth.controller;

import com.itrip.auth.exception.LoginNotFountException;
import com.itrip.auth.service.LoginService;
import com.itrip.beans.domain.ItripUser;
import com.itrip.beans.dto.Dto;
import com.itrip.utils.DtoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @PostMapping("/dologin")
    public Dto login(String name, String password, HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        try {
            ItripUser user = loginService.login(name, password);
            if(user != null) {
                return DtoUtil.returnSuccess("登录成功", loginService.createToken(user, userAgent));
            }else{
                return DtoUtil.returnFail("登录失败","30002");
            }
        }catch (LoginNotFountException ex){
            return DtoUtil.returnFail(ex.getMessage(),"30002");
        }
    }
}
